package hjw.com.controller.tea;

import hjw.com.dao.*;
import hjw.com.entity.Course;
import hjw.com.entity.TaskInfo;
import hjw.com.entity.User;
import hjw.com.entity.mark.Mark;
import hjw.com.entity.mark.MarkInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.*;

@Controller
@RequestMapping("/tea")
@SuppressWarnings("all")
public class TeaController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    TaskMapper taskMapper;
    @Autowired
    ClzMapper clzMapper;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    MarkMapper markMapper;

    @GetMapping("/go2Update")
    public String go2Update(){
        return "tea/update";
    }

    @PostMapping("/doUpdate")
    public String doUpdate(String name, String phone,
                           String pwd, HttpServletRequest req, Model model){
        //无数据传参拦截修改
        if (name == null && pwd == null){
            model.addAttribute("state","提示：未作修改!!!");
            return "main/index";
        }

        //获取session当前用户信息
        User user = (User) req.getSession().getAttribute("user");

        //判断数据是否修改
        if (!pwd.equals(user.getPwd())|| !phone.equals(user.getPhone()) || !name.equals(user.getUname())){
            String oldName = user.getUname();
            String odlPhone = user.getPhone();
            String oldPwd = user.getPwd();
            if (!name.equals(user.getUname())){
                // 有且仅有名字修改，更新session信息
                user.setUname(name);
            }
            if (!phone.equals(user.getPhone())){
                // 有且仅有手机号修改，更新session信息
                user.setPhone(phone);
            }
            if (!pwd.equals(user.getPwd())){
                // 有且仅有密码修改，更新session信息
                user.setPwd(pwd);
            }
            int key = 0;
            try {
                key = userMapper.updateById(user);
            } catch (Exception e) {
                model.addAttribute("state","数据提示：手机号已存在!!!");
                return "main/index";
            }

            if (key <= 0){
                //数据回溯，修改失败
                user.setUname(oldName);
                user.setPhone(odlPhone);
                user.setPwd(oldPwd);
                model.addAttribute("state","数据提示：修改失败!!!");
            }else {
                model.addAttribute("state","数据提示：修改成功!!!");
            }
            return "main/index";
        }
        model.addAttribute("state","提示：未作修改!!!");
        return "main/index";
    }

    @GetMapping("/doMain")
    public String main(HttpSession session, Model model){
        User user = (User)session.getAttribute("user");
        System.out.println(user);
        List<TaskInfo> taskInfos = taskMapper.findById(user.getUid());
        System.out.println(taskInfos);
        model.addAttribute("taskInfos",taskInfos);
        return "tea/main";
    }

    @PostMapping("/doFind")
    public String dofind(String clzno, String cno, Model model){
        System.out.println("clzno=" + clzno);
        System.out.println("cno=" + cno);
        List<MarkInfo> markInfos = new ArrayList<>();
        //查询获取班级名称
        Course course = courseMapper.findByCno(cno);

        // 查找该班级学生
        List<Map<String, Object>> stus = userMapper.findStudents(clzno);

        // 查找该班级已录入对应 sno, cno 的分数进行拼接
        for(Map<String, Object> s : stus) {
            MarkInfo markInfo = new MarkInfo();
            //班级编号
            markInfo.setClzno(clzno);
            //课程信息
            markInfo.getCourse().setCno(cno);
            markInfo.getCourse().setCname(course.getCname());
            //学生基本信息
            markInfo.setSno((String)s.get("phone"));
            markInfo.setSname((String) s.get("uname"));
            //初始化成绩信息
            markInfo.setId(0);
            markInfo.setScore(0);

            Mark k = markMapper.findBySno(markInfo.getSno(), cno);
            //成绩存在否
            if (k!=null) {
                markInfo.setScore(k.getScore());
                markInfo.setId(k.getId());
                markInfo.setTpost(k.getTpost());
            }

            markInfos.add(markInfo);
        }
        model.addAttribute("clzno",clzno);
        model.addAttribute("course",course);
        model.addAttribute("marks",markInfos);
        return "tea/show";
    }

    @RequestMapping("/doAdd")
    public String doAdd(MarkInfo markInfo, Model model){
        if (markInfo.getScore() < 0 || markInfo.getScore() >100){
            model.addAttribute("err", "(无效成绩，请重新输入)");
            return "forward:/tea/doFind?cno="+ markInfo.getCourse().getCno();
        }
        int key = 0;
        // id  !=0， 表示已有记录， 更新即可
        if (markInfo.getId() != 0) {
            key = markMapper.UpdateById(String.valueOf(markInfo.getId()),markInfo.getCourse().getCno(), String.valueOf(markInfo.getScore()));
        }
        // id  ==0， 表示成绩为空，需要添加
        if (markInfo.getId() == 0){
            key = markMapper.addMark(markInfo);
        }
        model.addAttribute("err",key > 0 ? "(成绩添加成功)":"(成绩修改失败)");

        return "forward:/tea/doFind?cno="+ markInfo.getCourse().getCno();

    }
}
